package com.dmjj.login.controller;

import com.alibaba.fastjson.JSON;
import com.dmjj.common.base.BaseController;
import com.dmjj.common.base.LoginEntity;
import com.dmjj.common.md5.Md5Util;
import com.dmjj.common.redisc.RedisUtil;
import com.dmjj.common.result.ResultEnum;
import com.dmjj.common.result.ResultObject;
import com.dmjj.common.util.ScanPool;
import com.dmjj.common.vo.ResultVO;
import com.dmjj.login.config.PoolCache;
import com.dmjj.login.config.ScanCounter;
import com.dmjj.login.service.LoginService;
import com.dmjj.login.vo.StoreVO;
import com.dmjj.util.annoation.SysLogger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * @Description: 登录
 * @author 王丽凯
 * @date 2019/3/15
 */
@Controller
@CrossOrigin
@Api(tags = "登录控制器")
@RequestMapping(value = "goDMJJLogin")
public class LoginController extends BaseController{

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LoginService loginService;
    @Autowired
    private ResultObject resultObject;


    /**
     * @Description: 登录页面token
     * @author 王丽凯
     * @date 2019/3/15
     */
    @GetMapping(value = "/getToken", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "登录页面获取token")
    @ResponseBody
    @SysLogger
    public String getToken(){
        String uuid = UUID.randomUUID().toString();
        redisUtil.set(uuid, new ScanPool(), 35);
        PoolCache.cacheMap.put(uuid,new ScanPool());
        return uuid;
    }

    /**
     * @Description: 扫码登录
     * @author 王丽凯
     * @date 2019/3/15
     */
    @PostMapping(value = "/scanLogin", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "扫码登录", response = LoginEntity.class)
    @ResponseBody
    @SysLogger
    public ResultVO<Object> scanLogin(LoginEntity loginEntity){
        String token = loginEntity.getToken();
        String userNo = loginEntity.getUserid();
        ScanPool scanPool = null;
        if (!StringUtils.isEmpty(token)&&!StringUtils.isEmpty(userNo)){

            if (!(PoolCache.cacheMap==null || PoolCache.cacheMap.isEmpty())){
                scanPool = PoolCache.cacheMap.get(token);
            }
            if (scanPool == null){
                return resultObject.error(ResultEnum.CODEINVALID.getCode(), ResultEnum.CODEINVALID.getMsg());
            }else {
                Map<String, Object> userMap = loginService.getUserInfoByNO(Integer.valueOf(userNo));
                if(userMap==null){
                    return resultObject.error(ResultEnum.FAIL.getCode(),"登陆失败，该用户不存在");
                }
                LoginEntity scanLoginEntity = mapToLoginEntity(userMap, token);
                scanLoginEntity.setLogin(3);
                scanPool.setLoginEntity(scanLoginEntity);
                scanPool.notifyPool();
                return resultObject.success(ResultEnum.SUCCESSSCAN.getCode(),ResultEnum.SUCCESSSCAN.getMsg());
            }
        }else {
            return resultObject.error(ResultEnum.FAILPARAM.getCode(), ResultEnum.FAILPARAM.getMsg());
        }
    }

    /**
     * @Description: 手机确认登录
     * @author 王丽凯
     * @date 2019/3/19
     */
    @GetMapping(value = "/confirmLogin", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "手机确认登录", response = LoginEntity.class)
    @ResponseBody
    @SysLogger(value = "手机确认登录")
    public String confirmLogin(HttpServletRequest request){
        String param = request.getParameter("data");
        String callbackparam = request.getParameter("callback");
        LoginEntity loginEntity = new LoginEntity();
        Map resultMap = new HashMap();
        if (!param.isEmpty()){
            Map mapType = JSON.parseObject(param,Map.class);
            String token = mapType.get("token")!=null?mapType.get("token").toString():null;
            String userid = mapType.get("userid")!=null?mapType.get("userid").toString():null;
            loginEntity.setToken(token);
            loginEntity.setUserid(userid);
        }
        String token = loginEntity.getToken();
        String userNo = loginEntity.getUserid();
        ScanPool scanPool = null;
        if (!StringUtils.isEmpty(token)&&!StringUtils.isEmpty(userNo)){
            scanPool = PoolCache.getScanPool(token);

            //获取个人信息
            Map<String, Object> userMap = loginService.getUserInfoByNO(Integer.valueOf(userNo));
            LoginEntity scanLoginEntity = mapToLoginEntity(userMap, token);
            scanLoginEntity.setLogin(3);
            scanPool.setLoginEntity(scanLoginEntity);

            if (scanPool == null){
                resultMap.put("code",ResultEnum.CODEINVALID.getCode());
                resultMap.put("msg",ResultEnum.CODEINVALID.getMsg());
                return callbackparam + "(" + JSON.toJSONString(resultMap) + ")";
            }else {
                scanPool.scanSuccess();
                LoginEntity redisLoginEntity = scanPool.getLoginEntity();
                if (Integer.parseInt(userNo) == Integer.parseInt(redisLoginEntity.getUserid())){
                    redisUtil.set(token,redisLoginEntity,24*60*60);
                    PoolCache.cleanValue(token);
                    resultMap.put("code",ResultEnum.SUCCESS.getCode());
                    resultMap.put("msg",ResultEnum.SUCCESS.getMsg());
                    return callbackparam + "(" + JSON.toJSONString(resultMap) + ")";
                }else {
                    resultMap.put("code",ResultEnum.FAILPARAM.getCode());
                    resultMap.put("msg",ResultEnum.FAILPARAM.getMsg());
                    return callbackparam + "(" + JSON.toJSONString(resultMap) + ")";
                }
            }
        }else {
            resultMap.put("code",ResultEnum.FAILPARAM.getCode());
            resultMap.put("msg",ResultEnum.FAILPARAM.getMsg());
            return callbackparam + "(" + JSON.toJSONString(resultMap) + ")";
        }
    }

    /**
     * @Description: 手机取消登录
     * @author 王丽凯
     * @date 2019/3/19
     */
    @PostMapping(value = "/cancelLogin", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "手机端取消登录", response = LoginEntity.class)
    @ResponseBody
    @SysLogger(value = "手机端取消登录")
    public ResultVO<Object> cancelLogin(LoginEntity loginEntity){
        String token = loginEntity.getToken();
        String userNo = loginEntity.getUserid();
        ScanPool scanPool = null;
        if (!StringUtils.isEmpty(token)&&!StringUtils.isEmpty(userNo)){
           scanPool = PoolCache.getScanPool(token);
            if (scanPool!=null){
                LoginEntity cacheLoginEntity = scanPool.getLoginEntity();
                if (Integer.parseInt(cacheLoginEntity.getUserid())==Integer.parseInt(userNo)){
                    cacheLoginEntity.setLogin(4);
                    scanPool.setLoginEntity(cacheLoginEntity);
                    scanPool.notifyPool();
                    /*PoolCache.cacheMap.remove(token);
                    if (isHaveToken(token)){
                        redisUtil.del(token);
                    }*/
                    return resultObject.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg());
                }else {
                    return resultObject.error(ResultEnum.NOTMYSELF.getCode(),ResultEnum.NOTMYSELF.getMsg());
                }
            }else {
                /*if (isHaveToken(token)){
                    redisUtil.del(token);
                }*/
                return resultObject.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg());
            }
        }else {
            return resultObject.error(ResultEnum.FAILPARAM.getCode(), ResultEnum.FAILPARAM.getMsg());
        }
    }

    /**
     * @Description: 前台轮询扫描状态
     * @author 王丽凯
     * @date 2019/3/15
     */
    @PostMapping(value = "/getScanStatus", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "轮询登录状态", response = LoginEntity.class)
    @ResponseBody
    @SysLogger(value = "轮询登录状态")
    public ResultVO<Object> getScanStatus(LoginEntity loginEntity){

        String token = loginEntity.getToken();
        ScanPool scanPool ;
        if (!StringUtils.isEmpty(token)){
            scanPool = PoolCache.getScanPool(token);
            try {

                if (scanPool == null){
                    Thread.sleep(3 * 1000L);
                    return resultObject.error(ResultEnum.CODEINVALID.getCode(), ResultEnum.CODEINVALID.getMsg());
                }else {
                    new Thread(new ScanCounter(token, scanPool)).start();

                    boolean scanFlag = scanPool.getScanStatus();

                    if (scanFlag&&scanPool.getLoginEntity().getLogin()==3){
                        return resultObject.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg(),scanPool.getLoginEntity());
                    }else {
                        if (scanPool.getLoginEntity()!=null){
                            if (scanPool.getLoginEntity().getLogin()==3){
                                return resultObject.success(ResultEnum.SUCCESSSCAN.getCode(),ResultEnum.SUCCESSSCAN.getMsg());
                            }
                            if (scanPool.getLoginEntity().getLogin()==4){
                                return resultObject.success(ResultEnum.CANCELLOGIN.getCode(),ResultEnum.CANCELLOGIN.getMsg());
                            }
                        }
                        return resultObject.error(ResultEnum.CODEWAIT.getCode(),ResultEnum.CODEWAIT.getMsg());
                    }
                }

            }catch (Exception e){
                e.printStackTrace();
                return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
            }
        }else {
            return resultObject.error(ResultEnum.FAILPARAM.getCode(), ResultEnum.FAILPARAM.getMsg());
        }
    }

    @PostMapping(value="/goPcLogin",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "PC登录接口", response = LoginEntity.class)
    @ResponseBody
    @SysLogger
    public ResultVO<Object> goPcLogin(LoginEntity loginEntity){
        String LoginUserid = loginEntity.getUserid();
        String LoginPassword = loginEntity.getPassword();
        if(LoginUserid==null||"".equals(LoginUserid)||LoginPassword==null||"".equals(LoginPassword)){
            return resultObject.error(ResultEnum.FAIL.getCode(),"登陆失败，缺少传入信息");
        }
        LoginPassword = Md5Util.getSha1(LoginPassword);
        //如果从前端获取的token在redis不存在，则通过userid从数据库中查询，进行校对
        Map<String, Object> userMap = loginService.getUserInfoByNO(Integer.parseInt(LoginUserid));
        if(userMap==null){
            return resultObject.error(ResultEnum.FAIL.getCode(),"登陆失败，该用户不存在");
        }
        String password = userMap.get("password")!=null?userMap.get("password").toString():null;
        if(!LoginPassword.equals(password)){
            return resultObject.error(ResultEnum.FAIL.getCode(),"登陆失败，密码不正确");
        }
        String token = UUID.randomUUID().toString();
        LoginEntity resultLogin = mapToLoginEntity(userMap,token);
        redisUtil.set(token,resultLogin,24*60*60);
        return resultObject.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg(),resultLogin);
    }

    @PostMapping(value="/quitPcLogin",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "PC退出登录接口传入token", response = LoginEntity.class)
    @ResponseBody
    @SysLogger
    public ResultVO<Object> quitPcLogin(LoginEntity loginEntity){
        loginEntity = getUserInfo();
        if(loginEntity!=null){
            String token = loginEntity.getToken();
            redisUtil.del(token);
            return resultObject.success(ResultEnum.SUCCESS.getCode(),"退出成功");
        }
        return resultObject.error(ResultEnum.FAIL.getCode(),"请传入token");
    }

    @PostMapping(value="/updatePassword",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "修改密码", response = LoginEntity.class)
    @ResponseBody
    @SysLogger
    public ResultVO<Object> updatePassword(LoginEntity loginEntity){
        if (loginEntity!=null&&!StringUtils.isEmpty(loginEntity.getPassword())){
            loginEntity.setPassword(Md5Util.getSha1(loginEntity.getPassword()));
            if (loginService.updatePassword(loginEntity)==1){
                return resultObject.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg());
            }else {
                return resultObject.error(ResultEnum.FAIL.getCode(),ResultEnum.FAIL.getMsg());
            }
        }
        return resultObject.error(ResultEnum.FAILPARAM.getCode(), ResultEnum.FAILPARAM.getMsg());
    }

    public LoginEntity mapToLoginEntity(Map<String,Object> userMap, String token){
        LoginEntity loginEntity = new LoginEntity();
        loginEntity.setToken(token);
        loginEntity.setUserid(userMap.get("ygNo").toString());
        loginEntity.setName((String) userMap.get("name"));
        loginEntity.setStore((String) userMap.get("store"));
        loginEntity.setBm(userMap.get("bm").toString());
        return loginEntity;
    }

    public boolean isHaveToken(String token){
        return redisUtil.hasKey(token);
    }
    
    
    
    /**
     * @Author zhangxue
     * @Description //TODO 获取所有中心店面
     * @Date 10:18 2019/4/17
     * @Param 
     * @return 
     **/
    @PostMapping(value="/queryAllStores",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "获取所有中心店面")
    @ResponseBody
    @SysLogger
    public ResultVO<Object> queryAllStores(LoginEntity loginEntity){
        List<Map<String,Object>> resultList = loginService.queryAllStores(loginEntity);
        return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),resultList);
    }

    /**
     * @Author zhangxue
     * @Description //TODO 通过中心店面Id查询包含所有部门
     * @Date 10:18 2019/4/17
     * @Param
     * @return
     **/
    @PostMapping(value="/queryAllBmByStoreId",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "通过中心店面Id查询包含所有部门")
    @ResponseBody
    @SysLogger
    public ResultVO<Object> queryAllBmByStoreId(StoreVO storeVO){
        List<Map<String,Object>> resultList = loginService.queryAllBmByStoreId(storeVO);
        return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),resultList);
    }

    /**
     * @Author zhangxue
     * @Description //TODO 通过部门Id查询该部门员工
     * @Date 10:18 2019/4/17
     * @Param
     * @return
     **/
    @PostMapping(value="/queryUserByBm",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "通过部门Id查询该部门员工")
    @ResponseBody
    @SysLogger
    public ResultVO<Object> queryUserByBm(StoreVO storeVO){
        List<Map<String,Object>> resultList = loginService.queryUserByBm(storeVO);
        return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),resultList);
    }


}
